package com.bruce.structure.linkedlist;

/**
 * @author luotuan
 * @Description 简单的单链表
 * @create 2021-04-21 15:18
 **/
public class SimpleLinkedList<T> {
    private Node<T> head;
    private Node<T> last;
    private int size;

    private void insert(T data, int index) {
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException("超出链表范围");
        }
        Node<T> currentNode = new Node<>(data);
        if (size == 0) {
            head = currentNode;
            last = currentNode;
        }
        else if (index == 0) {
            currentNode.next = head;
            head = currentNode;
        }
        else if (index == size) {
            last.next = currentNode;
            last = currentNode;
        }
        else {
            Node<T> indexNode = get(index - 1);
            currentNode.next = indexNode.next;
            indexNode.next = currentNode;
        }
        size++;
    }

    private void insert(T data){
        insert(data,size);
    }

    private Node<T> remove(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException("超出链表范围");
        }
        Node<T> removeNode = null;
        if (index == 0) {
            removeNode = head;
            head = head.next;
        }
        else if (index == size - 1) {
            Node<T> preNode = get(index - 1);
            removeNode = preNode.next;
            preNode.next = null;
            last = preNode;
        }
        else {
            Node<T> preNode = get(index - 1);
            removeNode = preNode.next;
            preNode.next = preNode.next.next;
        }
        size--;
        return removeNode;
    }

    public void output(){
        Node temp = head;
        while (temp!=null){
            System.out.println(temp.t);
            temp = temp.next;
        }
    }

    public static void main(String[] args) {
        SimpleLinkedList<Integer> simpleLinkedList = new SimpleLinkedList<Integer>();
        simpleLinkedList.insert(1);
        simpleLinkedList.insert(2);
        simpleLinkedList.insert(3);
        simpleLinkedList.insert(4);
        simpleLinkedList.remove(1);
        simpleLinkedList.output();
        System.out.println(1%11);
    }

    private Node<T> get(int index) {
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException("超出链表范围");
        }
        Node<T> temp = head;
        for (int i = 0; i < index; i++) {
            temp = temp.next;
        }
        return temp;
    }

    private static class Node<T> {
        T t;
        Node next;

        public Node(T t) {
            this.t = t;
        }
    }
}
